#!/usr/bin/python2
# -*- coding: utf-8 -*-

import re

reg_ok_smi = re.compile(r'^[^\+-\.]*$')

def sdf2list(sdf_string, smi_filter = None):
    '''parse the sdf string into list contains info of mols stored in  dicts'''

    l = ""
    line = ""
    sdfs = []
    all_smi = []
    result_list = []

    for line in sdf_string.replace('\r', '').split('\n'):
        line += "\n"
        if (line.startswith("$$$$")) and l:
            sdfs.append(l)
            l = ""
        elif not line.startswith("$$$$"):
            l += line
    if l.replace('\r', '').replace('\n', '').replace('\t', '').replace(' ', '') != '':
        sdfs.append(l)
        l = ""

    for string in sdfs:
        L = []
        tmpl = string.split("> <")
        if len(tmpl) == 1:
            tmpl = string.split(">  <")
        L = [i.strip().split(">", 1) for i in tmpl]
        L[0].insert(0, "mol_2d_struc")
        L = [(j[0].strip(), j[1].split(')')[-1].strip()) for j in L]
        try:
            dic = dict(L)
        except:
            L.pop()
            dic = dict(L)
        if dic.has_key('PUBCHEM_COMPOUND_CID'):
            dic['mol_id'] = dic['PUBCHEM_COMPOUND_CID']

        if dic.has_key('PUBCHEM_OPENEYE_CAN_SMILES'):
            smi = dic['PUBCHEM_OPENEYE_CAN_SMILES']
            if not smi in all_smi:
                if smi_filter:
                    if smi_filter(smi):
                        result_list.append(dic)
                    else:
                        pass
                        #print smi
                else:
                    result_list.append(dic)
        else:
            result_list.append(dic)

    return result_list

def smi_filter(smiles):
    if reg_ok_smi.match(smiles):
        return True
    return False
